package com.hong.spring.listener;

import com.alibaba.fastjson.JSONObject;
import com.hong.spring.api.IUserService;
import com.hong.spring.entity.User;
import com.hong.spring.utils.DataResponse;
import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.protocol.RemotingSerializable;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author: csh
 * @Date: 2021/3/16 11:14
 * @Description:用户监听
 */
@Log4j2
public class UserListener implements MessageListenerConcurrently {

    @Autowired
    private IUserService userService;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

            try {
                for (MessageExt msg : msgs) {
                User user = RemotingSerializable.decode(msg.getBody(), User.class);
                    log.info("获取的用户信息{}", JSONObject.toJSONString(user));
                    DataResponse <Boolean> save = userService.save(user);
                    if(save==null || save.getData()==null || !save.getData()){
                        log.info("添加失败，原因{}",JSONObject.toJSONString(save));
                        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                    }
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }catch (Exception e){
                log.error("添加用户异常{}",e);
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
    }
}
